/**
 * 链表节点类
 */
class StudentNode {
    Student data; // 存储学生对象
    StudentNode next; // 指向下一个节点的引用

    public StudentNode(Student data) {
        this.data = data;
        this.next = null;
    }
}

/**
 * 链表实现的成绩管理
 * 使用单链表存储学生成绩信息
 */
public class LinkedGradeManagement implements GradeManagementInterface {
    private StudentNode head; // 链表头节点
    private int count; // 当前学生人数

    /**
     * 构造方法：初始化空链表
     */
    public LinkedGradeManagement() {
        this.head = null;
        this.count = 0;
    }

    @Override
    public boolean isEmpty() {
        return head == null;
    }

    @Override
    public boolean isFull() {
        // 链表理论上不会满（除非内存不足）
        return false;
    }

    @Override
    public int size() {
        return count;
    }

    @Override
    public boolean add(Student student) {
        if (student == null) {
            return false;
        }
        // 检查是否已存在相同学号的学生
        if (findById(student.getStudentId()) != null) {
            System.out.println("学号 " + student.getStudentId() + " 已存在，添加失败");
            return false;
        }
        // 创建新节点
        StudentNode newNode = new StudentNode(student);
        // 如果链表为空，新节点作为头节点
        if (isEmpty()) {
            head = newNode;
        } else {
            // 找到链表尾部，插入新节点
            StudentNode current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
        count++;
        return true;
    }

    @Override
    public Student findById(String studentId) {
        StudentNode current = head;
        while (current != null) {
            if (current.data.getStudentId().equals(studentId)) {
                return current.data;
            }
            current = current.next;
        }
        return null;
    }

    @Override
    public Student get(int index) {
        if (index < 0 || index >= count) {
            throw new IndexOutOfBoundsException("索引越界: " + index);
        }
        StudentNode current = head;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        return current.data;
    }

    @Override
    public boolean remove(String studentId) {
        if (isEmpty()) {
            return false;
        }
        // 如果要删除的是头节点
        if (head.data.getStudentId().equals(studentId)) {
            head = head.next;
            count--;
            return true;
        }
        // 查找要删除的节点
        StudentNode current = head;
        while (current.next != null) {
            if (current.next.data.getStudentId().equals(studentId)) {
                current.next = current.next.next;
                count--;
                return true;
            }
            current = current.next;
        }
        return false;
    }

    @Override
    public void sortByScore() {
        // 使用冒泡排序（按综合成绩从高到低）
        if (count <= 1) {
            return;
        }
        // 将链表转换为数组进行排序，然后再转回链表
        Student[] tempArray = new Student[count];
        StudentNode current = head;
        for (int i = 0; i < count; i++) {
            tempArray[i] = current.data;
            current = current.next;
        }

        // 排序
        for (int i = 0; i < count - 1; i++) {
            for (int j = 0; j < count - 1 - i; j++) {
                if (tempArray[j].getComprehensiveScore() < tempArray[j + 1].getComprehensiveScore()) {
                    Student temp = tempArray[j];
                    tempArray[j] = tempArray[j + 1];
                    tempArray[j + 1] = temp;
                }
            }
        }

        // 更新排名并重建链表
        head = null;
        count = 0;
        for (int i = 0; i < tempArray.length; i++) {
            tempArray[i].setRank(i + 1);
            add(tempArray[i]);
        }

        // 修复：因为add方法会增加count，需要重置
        // 重新构建链表，不使用add方法
        head = null;
        count = 0;
        for (int i = 0; i < tempArray.length; i++) {
            StudentNode newNode = new StudentNode(tempArray[i]);
            if (head == null) {
                head = newNode;
            } else {
                StudentNode current2 = head;
                while (current2.next != null) {
                    current2 = current2.next;
                }
                current2.next = newNode;
            }
            count++;
        }
    }

    @Override
    public void evaluateScholarship(double firstPrizeRatio, double secondPrizeRatio, double thirdPrizeRatio) {
        // 先按成绩排序
        sortByScore();

        // 计算各等级人数（向下取整）
        int total = count;
        int firstPrizeCount = (int) Math.floor(total * firstPrizeRatio);
        int secondPrizeCount = (int) Math.floor(total * secondPrizeRatio);
        int thirdPrizeCount = (int) Math.floor(total * thirdPrizeRatio);

        // 评定奖学金
        StudentNode current = head;
        int index = 0;
        while (current != null) {
            if (index < firstPrizeCount) {
                current.data.setScholarship("一等奖");
            } else if (index < firstPrizeCount + secondPrizeCount) {
                current.data.setScholarship("二等奖");
            } else if (index < firstPrizeCount + secondPrizeCount + thirdPrizeCount) {
                current.data.setScholarship("三等奖");
            } else {
                current.data.setScholarship("无");
            }
            current = current.next;
            index++;
        }
    }

    @Override
    public void displayAll() {
        if (isEmpty()) {
            System.out.println("成绩表为空");
            return;
        }
        System.out.println("========== 所有学生成绩信息 ==========");
        System.out.println(String.format("%-8s %-6s %-8s %-15s %-10s %-6s %-10s",
                "学号", "姓名", "班级", "各科成绩", "综合成绩", "排名", "奖学金"));
        System.out.println("-----------------------------------------------------------");
        StudentNode current = head;
        while (current != null) {
            Student s = current.data;
            StringBuilder scoresStr = new StringBuilder("[");
            double[] scores = s.getCourseScores();
            for (int j = 0; j < scores.length; j++) {
                scoresStr.append(String.format("%.2f", scores[j]));
                if (j < scores.length - 1) {
                    scoresStr.append(", ");
                }
            }
            scoresStr.append("]");
            System.out.println(String.format("%-8s %-6s %-8s %-15s %-10.2f %-6d %-10s",
                    s.getStudentId(), s.getName(), s.getClassName(),
                    scoresStr.toString(), s.getComprehensiveScore(),
                    s.getRank(), s.getScholarship()));
            current = current.next;
        }
        System.out.println("==========================================");
    }

    @Override
    public void displayScholarshipWinners() {
        if (isEmpty()) {
            System.out.println("成绩表为空");
            return;
        }
        System.out.println("========== 获奖学生名单 ==========");
        boolean hasWinner = false;
        StudentNode current = head;
        while (current != null) {
            if (!current.data.getScholarship().equals("无")) {
                hasWinner = true;
                System.out.println(current.data.toString());
            }
            current = current.next;
        }
        if (!hasWinner) {
            System.out.println("暂无获奖学生");
        }
        System.out.println("====================================");
    }

    @Override
    public void clear() {
        head = null;
        count = 0;
    }

    @Override
    public void merge(GradeManagementInterface other) {
        if (other == null) {
            return;
        }
        int otherSize = other.size();
        for (int i = 0; i < otherSize; i++) {
            Student student = other.get(i);
            // 创建新学生对象，避免引用冲突
            Student newStudent = new Student(
                    student.getStudentId(),
                    student.getName(),
                    student.getClassName(),
                    student.getCourseScores());
            add(newStudent);
        }
    }
}

